﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace EVTEST
{
    public class EVOBD_tc:EVOBDParent
    {/// <summary>
     /// 用于UDP发送的网络服务类
     /// </summary>
        //private UdpClient udpcSend;

        /// <summary>
        /// 用于UDP接收的网络服务类
        /// </summary>
        //private UdpClient udpcRecv;
        IPAddress HostIP = IPAddress.Parse("127.0.0.1");
        int HostPort = 10056;
        IPEndPoint point;
        private static Socket socket;
        bool flag = true;
        Socket acceptedSocket;


        private string receivedString = "";
        private bool receivedFlag = false;
        Thread thread = null;

        private bool receivedflag = false;
        static int sendOutTime = 10;
        static int receiveOutTime = 60;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public EVOBD_tc(string ip, string port)
        {
            HostIP = IPAddress.Parse(ip);
            HostPort = Int32.Parse(port);
            //initServer();
        }

        public EVOBD_tc()
        {
            //initServer();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public void initSocket(string ip, string port)
        {
            HostIP = IPAddress.Parse(ip);
            HostPort = Int32.Parse(port);
        }



        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool init_equipment(out string msg)
        {
            msg = "";
            try
            {
                point = new IPEndPoint(HostIP, HostPort);
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(point);
                if (myLED_OBD_connected != null) myLED_OBD_connected.Invoke(new Action(() => { if (myLED_OBD_connected != null) myLED_OBD_connected.IsLightLed = true; }));
                LogWrite.WriteInfo("初始化连接成功");
                return true;
            }
            catch (Exception ey)
            {
                msg = ey.Message;
                LogWrite.WriteError("初始化连接失败");
                if (myLED_OBD_connected != null) myLED_OBD_connected.Invoke(new Action(() => { if (myLED_OBD_connected != null) myLED_OBD_connected.IsLightLed = false; }));
                return false;
            }
        }
        private bool reconnect()
        {
            try
            {
                if (socket != null) socket.Close();
                point = new IPEndPoint(HostIP, HostPort);
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(point);
                if (myLED_OBD_connected != null) myLED_OBD_connected.Invoke(new Action(() => { if (myLED_OBD_connected != null) myLED_OBD_connected.IsLightLed = true; }));
                LogWrite.WriteInfo("重新连接成功");
                return true;
            }
            catch (Exception ey)
            {
                LogWrite.WriteError("重新连接失败");
                if (myLED_OBD_connected != null) myLED_OBD_connected.Invoke(new Action(() => { if (myLED_OBD_connected != null) myLED_OBD_connected.IsLightLed = false; }));
                return false;
            }
        }
        /// <summary>
        /// 向远程主机发送数据
        /// </summary>
        /// <param name="socket">连接到远程主机的socket</param>
        /// <param name="buffer">待发送数据</param>
        /// <param name="outTime">发送超时时长，单位是秒(为-1时，将一直等待直到有数据需要发送)</param>
        /// <returns>0:发送成功；-1:超时；-2:出现错误；-3:出现异常</returns>
        public bool SendData(byte[] buffer, out string msg)
        {
            msg = "";
            if (socket == null || socket.Connected == false)
            {
                LogWrite.WriteError("参数socket为null，或者未连接到远程计算机");
                //if(myLED_OBD_connected!=null)myLED_OBD_connected.Invoke(new Action(() => { if(myLED_OBD_connected!=null)myLED_OBD_connected.IsLightLed = false; }));

                if (!reconnect())
                {
                    msg = "OBD未连接";
                    return false;
                }
            }
            if (buffer == null || buffer.Length == 0)
            {
                LogWrite.WriteError("发送数据失败，参数buffer为null ,或者长度为 0");
                msg = "发送数据失败，参数buffer为null ,或者长度为 0";
                return false;
            }

            int flag = 0;
            try
            {
                int left = buffer.Length;
                int sndLen = 0;
                int hasSend = 0;

                while (true)
                {
                    if ((socket.Poll(sendOutTime * 1000, SelectMode.SelectWrite) == true))
                    {
                        // 收集了足够多的传出数据后开始发送
                        sndLen = socket.Send(buffer, hasSend, left, SocketFlags.None);
                        left -= sndLen;
                        hasSend += sndLen;

                        // 数据已经全部发送
                        if (left == 0)
                        {
                            flag = 0;
                            msg = "发送成功";
                            return true;
                        }
                        else
                        {
                            // 数据部分已经被发送
                            if (sndLen > 0)
                            {
                                continue;
                            }
                            else // 发送数据发生错误
                            {
                                flag = -2;
                                msg = "发送数据发生错误";
                                return false;
                            }
                        }
                    }
                    else // 超时退出
                    {
                        flag = -1;
                        msg = "发送数据超时";
                        return false;
                    }
                }
            }
            catch (Exception er)
            {
                //Log
                LogWrite.WriteError("发送数据过程发生异常：" + er.Message);
                msg = "发送数据过程发生异常：" + er.Message;
                return false;
            }
            //return "发送完毕";
        }
        /// <summary>
        /// 向远程主机发送数据
        /// </summary>
        /// <param name="socket">连接到远程主机的socket</param>
        /// <param name="buffer">待发送的字符串</param>
        /// <param name="outTime">发送数据的超时时间，单位是秒(为-1时，将一直等待直到有数据需要发送)</param>
        /// <returns>0:发送数据成功；-1:超时；-2:错误；-3:异常</returns>
        public bool SendData(Socket socket, string buffer, out string msg)
        {
            return SendData(System.Text.Encoding.Default.GetBytes(buffer), out msg);
        }
        /// <summary>
        /// 接收远程主机发送的数据
        /// </summary>
        /// <param name="socket">要接收数据且已经连接到远程主机的</param>
        /// <param name="buffer">接收数据的缓冲区(需要接收的数据的长度，由 buffer 的长度决定)</param>
        /// <param name="outTime">接收数据的超时时间，单位秒(指定为-1时，将一直等待直到有数据需要接收)</param>
        /// <returns></returns>
        public int RecvData(Socket socket, out string receivedMessage)
        {
            byte[] buffer = new byte[10240];
            receivedMessage = "";
            if (socket == null || socket.Connected == false)
            {
                LogWrite.WriteError("socket为null，或者未连接到远程计算机");
                return 0;
            }
            buffer.Initialize();
            int left = buffer.Length;
            int curRcv = 0;
            int hasRecv = 0;
            int flag = 0;
            int receiveOutCount = 0;
            try
            {
                while (true)
                {
                    if (socket.Poll(receiveOutTime * 1000, SelectMode.SelectRead) == true)
                    {
                        // 已经有数据等待接收
                        curRcv = socket.Receive(buffer, hasRecv, left, SocketFlags.None);
                        left -= curRcv;
                        hasRecv += curRcv;
                        string s = System.Text.Encoding.UTF8.GetString(buffer, 0, hasRecv);
                        LogWrite.WriteInfo("接收到数据：" + s);
                        //string s = Encoding.gbk.GetString(buffer, 0, hasRecv);//将已接收到的转换化字符串，以"/Message"为结束判断
                        // 数据已经全部接收 
                        bool isReceiveFinished = (s.Trim()).EndsWith("#");
                        if (isReceiveFinished)
                        {
                            LogWrite.WriteInfo("内容正确");
                            receivedMessage = s.Substring(11, s.Length - 12);
                            flag = 1;
                            break;
                        }
                        else
                        {
                            LogWrite.WriteInfo("内容错误");
                            flag = 0;
                            break;
                        }
                        /*
                        else
                        {
                            LogWrite.WriteInfo("数据未接收完毕");
                            // 数据已经部分接收
                            if (curRcv > 0)
                            {
                                continue;
                            }
                            else  // 出现错误
                            {
                                flag = -2;
                                break;
                            }
                        }*/
                    }
                    else // 超时退出
                    {
                        Thread.Sleep(1000);
                        receiveOutCount++;
                        if (receiveOutCount >= receiveOutTime)
                        {
                            LogWrite.WriteInfo("接收数据超时");
                            flag = -1;
                            break;
                        }
                    }
                }
            }
            catch (SocketException)
            {
                //Log
                flag = -3;
            }
            return flag;
        }
        static byte[] ConvertJsonToString(JObject obj)
        {
            string jsonstr = JsonConvert.SerializeObject(obj);            
            byte[] bufferToSend = System.Text.Encoding.UTF8.GetBytes(jsonstr);
            int length = bufferToSend.Length + 12;
            string newstring = "ZDEPS" + length.ToString("000000") + jsonstr + "#";
            LogWrite.WriteInfo("SEND:\r\n" + newstring);
            byte[] bufferToSend2 = System.Text.Encoding.UTF8.GetBytes(newstring);
            return bufferToSend2;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="code">0-VCI在线 1-VCI不在线 2-VCI正在初始化 3-程序正在处理别的命令 -1-异常</param>
        /// <param name="msg"></param>
        /// <returns>true-获取成功 false-获取失败</returns>
        public override bool getVCIState(out string code, out string msg)
        {
            code = "0";
            msg = "";
            JObject ht = new JObject();
            JObject request = new JObject();
            JObject data = new JObject();
            request.Add("cmd", "GetVCIState");
            //request.Add("data", data);
            ht.Add("request", request);

            if (!SendData(ConvertJsonToString(ht), out msg))
            {
                return false;
            }
            Thread.Sleep(100);
            byte[] buffer = new byte[10 * 1024];
            string receivedString = "";
            if (RecvData(socket, out receivedString) > 0)
            {
                try
                {
                    JObject obj_ack = (JObject)JsonConvert.DeserializeObject(receivedString);
                    JObject response = (JObject)JsonConvert.DeserializeObject(obj_ack["response"].ToString());
                    code = response["code"].ToString();
                    msg = response["msg"].ToString();
                    return code=="0";
                }
                catch(Exception er)
                {
                    code = "-1";
                    msg = "解析发生异常:" + er.Message;
                    return false;
                }
            }
            else
            {
                msg = "接收数据失败";
                return false;
            }
        }
        public override bool getVersion(out string versionnumber, out string code, out string msg)
        {
            versionnumber = "";
            code = "0";
            msg = "";
            JObject ht = new JObject();
            JObject request = new JObject();
            JObject data = new JObject();
            request.Add("cmd", "GetSoftwareVersion");
            ht.Add(request);

            if (!SendData(ConvertJsonToString(ht), out msg))
            {
                return false;
            }
            Thread.Sleep(100);
            byte[] buffer = new byte[10 * 1024];
            string receivedString = "";
            if (RecvData(socket, out receivedString) > 0)
            {
                try
                {
                    JObject obj_ack = (JObject)JsonConvert.DeserializeObject(receivedString);
                    JObject response = (JObject)JsonConvert.DeserializeObject(obj_ack["response"].ToString());
                    code = response["code"].ToString();
                    msg = response["msg"].ToString();
                    if (code == "0")
                    {
                        JObject obj_data = (JObject)JsonConvert.DeserializeObject(response["data"].ToString());
                        versionnumber = obj_data["SoftwareVersion"].ToString();
                    }
                    return true;
                }
                catch (Exception er)
                {
                    code = "-1";
                    msg = "解析发生异常:" + er.Message;
                    return false;
                }
            }
            else
            {
                msg = "接收数据失败";
                return false;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="carbj"></param>
        /// <param name="code">0-VCI在线 1-VCI不在线 2-VCI正在初始化 3-程序正在处理别的命令 -1-异常</param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public override bool StartTest(EV_MODEL.CarbjModel carbj, out string code, out string msg)
        {
            code = "0";
            msg = "";
            JObject ht = new JObject();
            JObject request = new JObject();
            JObject data = new JObject();
            request.Add("cmd", "StartTest");
            data.Add("VIN", carbj.clsbdh);
            data.Add("Manufacture", carbj.clpp1);
            data.Add("Brand", carbj.clpp1);
            data.Add("Model", carbj.clxh);
            data.Add("PlateNumber", carbj.hphm);
            request.Add("data",data);
            ht.Add("request",request);

            if (!SendData(ConvertJsonToString(ht), out msg))
            {
                return false;
            }
            Thread.Sleep(100);
            byte[] buffer = new byte[10 * 1024];
            string receivedString = "";
            if (RecvData(socket, out receivedString) > 0)
            {
                try
                {
                    JObject obj_ack = (JObject)JsonConvert.DeserializeObject(receivedString);
                    JObject response = (JObject)JsonConvert.DeserializeObject(obj_ack["response"].ToString());
                    code = response["code"].ToString();
                    msg = response["msg"].ToString();
                    return code=="0";
                }
                catch (Exception er)
                {
                    code = "-1";
                    msg = "解析发生异常:" + er.Message;
                    return false;
                }
            }
            else
            {
                msg = "接收数据失败";
                return false;
            }
        }

        public override bool StopTest(out string code, out string msg)
        {
            code = "0";
            msg = "";
            JObject ht = new JObject();
            JObject request = new JObject();
            JObject data = new JObject();
            request.Add("cmd", "StopTest");
            //request.Add("data", data);
            ht.Add("request", request);

            if (!SendData(ConvertJsonToString(ht), out msg))
            {
                return false;
            }
            Thread.Sleep(100);
            byte[] buffer = new byte[10 * 1024];
            string receivedString = "";
            if (RecvData(socket, out receivedString) > 0)
            {
                try
                {
                    JObject obj_ack = (JObject)JsonConvert.DeserializeObject(receivedString);
                    JObject response = (JObject)JsonConvert.DeserializeObject(obj_ack["response"].ToString());
                    code = response["code"].ToString();
                    msg = response["msg"].ToString();
                    return true;
                }
                catch (Exception er)
                {
                    code = "-1";
                    msg = "解析发生异常:" + er.Message;
                    return false;
                }
            }
            else
            {
                msg = "接收数据失败";
                return false;
            }
        }
        public override bool GetDTCInfo(out int current,out List<string> GZDM, out List<string> GZXX, out string code, out string msg)
        {
            current = 0;
            code = "";
            msg = "";
            GZDM = new List<string>();
            GZXX = new List<string>();
            JObject ht = new JObject();
            JObject request = new JObject();
            JObject data = new JObject();
            request.Add("cmd", "GetDTCInfo");
            //request.Add("data", data);
            ht.Add("request", request);

            if (!SendData(ConvertJsonToString(ht), out msg))
            {
                return false;
            }
            Thread.Sleep(100);
            byte[] buffer = new byte[10 * 1024];
            string receivedString = "";
            if (RecvData(socket, out receivedString) > 0)
            {
                try
                {
                    JObject obj_ack = (JObject)JsonConvert.DeserializeObject(receivedString);
                    JObject response = (JObject)JsonConvert.DeserializeObject(obj_ack["response"].ToString());
                    code = response["code"].ToString();
                    msg = response["msg"].ToString();
                    if (code == "0")
                    {
                        JObject obj_data = (JObject)JsonConvert.DeserializeObject(response["data"].ToString());
                        current = int.Parse(obj_data["Current"].ToString());
                        for (int i= 1; i <= current;i++)
                        {
                            string dtc = obj_data["DTC" + i.ToString()].ToString();
                            string detail = obj_data["Detail" + i.ToString()].ToString();
                            GZDM.Add(dtc);
                            GZXX.Add(detail);
                        }
                    }
                    return true;
                }
                catch (Exception er)
                {
                    code = "-1";
                    msg = "解析发生异常:" + er.Message;
                    return false;
                }
            }
            else
            {
                msg = "接收数据失败";
                return false;
            }
        }
        public override bool GetLampState(out int LampState, out string code, out string msg)
        {
            LampState = 0;
            code = "";
            msg = "";
            JObject ht = new JObject();
            JObject request = new JObject();
            JObject data = new JObject();
            request.Add("cmd", "GetLampState");
            //request.Add("data", data);
            ht.Add("request", request);

            if (!SendData(ConvertJsonToString(ht), out msg))
            {
                return false;
            }
            Thread.Sleep(100);
            byte[] buffer = new byte[10 * 1024];
            string receivedString = "";
            if (RecvData(socket, out receivedString) > 0)
            {
                try
                {
                    JObject obj_ack = (JObject)JsonConvert.DeserializeObject(receivedString);
                    JObject response = (JObject)JsonConvert.DeserializeObject(obj_ack["response"].ToString());
                    code = response["code"].ToString();
                    msg = response["msg"].ToString();
                    if (code == "0")
                    {
                        JObject obj_data = (JObject)JsonConvert.DeserializeObject(response["data"].ToString());
                        LampState = int.Parse(obj_data["LampState"].ToString());
                    }
                    return true;
                }
                catch (Exception er)
                {
                    code = "-1";
                    msg = "解析发生异常:" + er.Message;
                    return false;
                }
            }
            else
            {
                msg = "接收数据失败";
                return false;
            }
        }
        private string getRTElement(string element,JObject obj)
        {
            if (obj[element] != null)
            {
                return obj[element].ToString();
            }
            else
                return "";
        }
        private double getMaxTemp(string a,string b,string c, string d,string e,string f,string g,string h)
        {
            List<double> templist = new List<double>();
            templist.Add(GetDouble(a));
            templist.Add(GetDouble(b));
            templist.Add(GetDouble(c));
            templist.Add(GetDouble(d));
            templist.Add(GetDouble(e));
            templist.Add(GetDouble(f));
            templist.Add(GetDouble(g));
            templist.Add(GetDouble(h));
            return templist.Max();
        }
        public override bool GetRTData(out EVOBDRealData model, out string code, out string msg)
        {
            model = new EVOBDRealData();
            code = "";
            msg = "";
            JObject ht = new JObject();
            JObject request = new JObject();
            JObject data = new JObject();
            request.Add("cmd", "GetRTData");
            //request.Add("data", data);
            ht.Add("request", request);

            if (!SendData(ConvertJsonToString(ht), out msg))
            {
                return false;
            }
            Thread.Sleep(100);
            byte[] buffer = new byte[10 * 1024];
            string receivedString = "";
            if (RecvData(socket, out receivedString) > 0)
            {
                try
                {
                    JObject obj_ack = (JObject)JsonConvert.DeserializeObject(receivedString);
                    JObject response = (JObject)JsonConvert.DeserializeObject(obj_ack["response"].ToString());
                    code = response["code"].ToString();
                    msg = response["msg"].ToString();
                    if (code == "0")
                    {
                        JObject obj_data = (JObject)JsonConvert.DeserializeObject(response["data"].ToString());
                        model.ODO=getRTElement("ODO", obj_data);
                        model.SOC = getRTElement("SOC", obj_data);
                        model.SOH = getRTElement("SOH", obj_data);
                        model.EnhanceSOH = getRTElement("EnhanceSOH", obj_data);
                        model.DCIR = getRTElement("DCIR", obj_data);
                        model.ACIR = getRTElement("ACIR", obj_data);
                        model.CurrentTotalV = getRTElement("CurrentTotalV", obj_data);
                        model.CurrentTotalI = getRTElement("CurrentTotalI", obj_data);
                        model.ChargingPower = getRTElement("ChargingPower", obj_data);
                        model.SpeedOfVehicle = getRTElement("SpeedOfVehicle", obj_data);
                        model.MotorTA = getRTElement("MotorTA", obj_data);
                        model.MotorTB = getRTElement("MotorTB", obj_data);
                        model.MotorTC = getRTElement("MotorTC", obj_data);
                        model.MotorTD = getRTElement("MotorTD", obj_data);
                        model.MotorTE = getRTElement("MotorTE", obj_data);
                        model.MotorTF = getRTElement("MotorTF", obj_data);
                        model.MotorTG = getRTElement("MotorTG", obj_data);
                        model.MotorTH = getRTElement("MotorTH", obj_data);
                        model.IGBTA = getRTElement("IGBTA", obj_data);
                        model.IGBTB = getRTElement("IGBTB", obj_data);
                        model.IGBTC = getRTElement("IGBTC", obj_data);
                        model.IGBTD = getRTElement("IGBTD", obj_data);
                        model.IGBTE = getRTElement("IGBTE", obj_data);
                        model.IGBTF = getRTElement("IGBTF", obj_data);
                        model.IGBTG = getRTElement("IGBTG", obj_data);
                        model.IGBH = getRTElement("IGBH", obj_data);
                        model.DCDCT = GetDouble(getRTElement("DC-DCT", obj_data));
                        model.PowerBatteryRealTimeT = getRTElement("PowerBatteryReal-TimeT", obj_data);
                        model.AccelerationPedalOpening = getRTElement("AccelerationPedalOpening", obj_data);
                        model.BreakPedalOpening = getRTElement("BreakPedalOpening", obj_data);
                        model.VoltageRange = getRTElement("VoltageRange", obj_data);
                        model.MaxVofSingleBattery = GetDouble(getRTElement("MaxVofSingleBattery", obj_data));
                        model.MaxVofSingleBatterySystemNumber = getRTElement("MaxVofSingleBatterySystemNumber", obj_data);
                        model.MaxVofSingleBatteryNumber = getRTElement("MaxVofSingleBatteryNumber", obj_data);
                        model.MinVofSingleBattery = GetDouble(getRTElement("MinVofSingleBattery", obj_data));
                        model.MinVofSingleBatterySystemNumber = getRTElement("MinVofSingleBatterySystemNumber", obj_data);
                        model.MinVofSingleBatteryNumber = getRTElement("MinVofSingleBatteryNumber", obj_data);
                        model.MaxTofSingleBattery = GetDouble(getRTElement("MaxTofSingleBattery", obj_data));
                        model.MaxTofSingleBatterySystemNumber = getRTElement("MaxTofSingleBatterySystemNumber", obj_data);
                        model.MaxTofSingleBatteryNumber = getRTElement("MaxTofSingleBatteryNumber", obj_data);
                        model.MinTofSingleBattery = getRTElement("MinTofSingleBattery", obj_data);
                        model.MinTofSingleBatterySystemNumber = getRTElement("MinTofSingleBatterySystemNumber", obj_data);
                        model.MinTofSingleBatteryNumber = getRTElement("MinTofSingleBatteryNumber", obj_data);
                        model.MotorTorque = getRTElement("MotorTorque", obj_data);
                        model.MotorSpeed = getRTElement("MotorSpeed", obj_data);
                        model.MotorBusV = getRTElement("MotorBusV", obj_data);
                        model.MotorBusI = getRTElement("MotorBusI", obj_data);
                        model.BusbarV = getRTElement("BusbarV", obj_data);
                        model.BatteryAlarmInfo = getRTElement("BatteryAlarmInfo", obj_data);
                        model.MotorAlarmInfo = getRTElement("MotorAlarmInfo", obj_data);
                        model.ElectronicControlAlarminfo = getRTElement("ElectronicControlAlarminfo", obj_data);
                        model.EngineRunTime = getRTElement("EngineRunTime", obj_data);
                        model.MILMileage = getRTElement("MILMileage", obj_data);
                        model.MILEngineRunTime = getRTElement("MILEngineRunTime", obj_data);

                        model.MaxTofMotor = getMaxTemp(model.MotorTA, model.MotorTB, model.MotorTC, model.MotorTD, model.MotorTE, model.MotorTF, model.MotorTG, model.MotorTH);

                        model.MaxTofMCS = getMaxTemp(model.IGBTA, model.MotorTB, model.MotorTC, model.MotorTD, model.MotorTE, model.MotorTF, model.MotorTG, model.MotorTH);
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception er)
                {
                    code = "-1";
                    msg = "解析发生异常:" + er.Message;
                    return false;
                }
            }
            else
            {
                msg = "接收数据失败";
                return false;
            }
        }

        public override bool GetBatteryNumber(out BatteryNumberModel model, out string code, out string msg)
        {
            model = new BatteryNumberModel();
            code = "";
            msg = "";
            JObject ht = new JObject();
            JObject request = new JObject();
            JObject data = new JObject();
            request.Add("cmd", "GetBatteryNumber");
            //request.Add("data", data);
            ht.Add("request", request);

            if (!SendData(ConvertJsonToString(ht), out msg))
            {
                return false;
            }
            Thread.Sleep(100);
            byte[] buffer = new byte[10 * 1024];
            string receivedString = "";
            if (RecvData(socket, out receivedString) > 0)
            {
                try
                {
                    JObject obj_ack = (JObject)JsonConvert.DeserializeObject(receivedString);
                    JObject response = (JObject)JsonConvert.DeserializeObject(obj_ack["response"].ToString());
                    code = response["code"].ToString();
                    msg = response["msg"].ToString();
                    if (code == "0")
                    {
                        JObject obj_data = (JObject)JsonConvert.DeserializeObject(response["data"].ToString());
                        model.BatteryNumberA = getRTElement("BatteryNumberA", obj_data);
                        model.BatteryNumberB = getRTElement("BatteryNumberB", obj_data);
                        model.BatteryNumberC = getRTElement("BatteryNumberC", obj_data);
                        model.BatteryNumberD = getRTElement("BatteryNumberD", obj_data);
                        model.BatteryNumberE = getRTElement("BatteryNumberE", obj_data);
                        model.BatteryNumberF = getRTElement("BatteryNumberF", obj_data);
                        model.BatteryNumberG = getRTElement("BatteryNumberG", obj_data);
                        model.BatteryNumberH = getRTElement("BatteryNumberH", obj_data);

                    }
                    return true;
                }
                catch (Exception er)
                {
                    code = "-1";
                    msg = "解析发生异常:" + er.Message;
                    return false;
                }
            }
            else
            {
                msg = "接收数据失败";
                return false;
            }
        }
        public override bool GetVIN(out string VIN, out string code, out string msg)
        {
            VIN = "";
            code = "";
            msg = "";
            JObject ht = new JObject();
            JObject request = new JObject();
            JObject data = new JObject();
            request.Add("cmd", "GetVIN");
            //request.Add("data", data);
            ht.Add("request", request);

            if (!SendData(ConvertJsonToString(ht), out msg))
            {
                return false;
            }
            Thread.Sleep(100);
            byte[] buffer = new byte[10 * 1024];
            string receivedString = "";
            if (RecvData(socket, out receivedString) > 0)
            {
                try
                {
                    JObject obj_ack = (JObject)JsonConvert.DeserializeObject(receivedString);
                    JObject response = (JObject)JsonConvert.DeserializeObject(obj_ack["response"].ToString());
                    code = response["code"].ToString();
                    msg = response["msg"].ToString();
                    if (code == "0")
                    {
                        JObject obj_data = (JObject)JsonConvert.DeserializeObject(response["data"].ToString());
                        VIN = getRTElement("VIN", obj_data);

                    }
                    return true;
                }
                catch (Exception er)
                {
                    code = "-1";
                    msg = "解析发生异常:" + er.Message;
                    return false;
                }
            }
            else
            {
                msg = "接收数据失败";
                return false;
            }
        }

        public override bool GetECUName(out string ECUName, out string code, out string msg)
        {
            ECUName = "";
            code = "";
            msg = "";
            JObject ht = new JObject();
            JObject request = new JObject();
            JObject data = new JObject();
            request.Add("cmd", "GetECUName");
            //request.Add("data", data);
            ht.Add("request", request);

            if (!SendData(ConvertJsonToString(ht), out msg))
            {
                return false;
            }
            Thread.Sleep(100);
            byte[] buffer = new byte[10 * 1024];
            string receivedString = "";
            if (RecvData(socket, out receivedString) > 0)
            {
                try
                {
                    JObject obj_ack = (JObject)JsonConvert.DeserializeObject(receivedString);
                    JObject response = (JObject)JsonConvert.DeserializeObject(obj_ack["response"].ToString());
                    code = response["code"].ToString();
                    msg = response["msg"].ToString();
                    if (code == "0")
                    {
                        JObject obj_data = (JObject)JsonConvert.DeserializeObject(response["data"].ToString());
                        ECUName = getRTElement("EcuName", obj_data);

                    }
                    return true;
                }
                catch (Exception er)
                {
                    code = "-1";
                    msg = "解析发生异常:" + er.Message;
                    return false;
                }
            }
            else
            {
                msg = "接收数据失败";
                return false;
            }
        }
        #region 实现OBD接口
        public override bool startService(out string msg)
        {
            LogWrite.WriteInfo("接口[开启服务]");
            if (init_equipment(out msg))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public override bool stopService(out string msg)
        {
            LogWrite.WriteInfo("接口[结束服务]");
            msg = "";
            try
            {
                if (socket != null)
                    socket.Close();
                return true;
            }
            catch (Exception er)
            {
                msg = er.Message;
                return false;
            }
        }
        
        #endregion
    }
}
